package ar.com.ford.it.fullEconomics.view.action;

import java.sql.Timestamp;
import java.util.Collection;
import java.util.LinkedList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.facade.CommodityFacade;
import ar.com.ford.it.fullEconomics.facade.RequestFacade;
import ar.com.ford.it.fullEconomics.facade.SupplierFacade;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesr01Request;
import ar.com.ford.it.fullEconomics.persistence.dto.Teess01Supplier;
import ar.com.ford.it.fullEconomics.struct.OptionCombo;
import ar.com.ford.it.fullEconomics.struct.RequestFindStruct;
import ar.com.ford.it.fullEconomics.util.FullEconomicsDateUtil;
import ar.com.ford.it.fullEconomics.view.form.RequestsForm;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.facade.FacadeProvider;
import ar.com.ford.it.webengine.struts.AbstractBaseAction;
import ar.com.ford.it.webengine.struts.FordActionMapping;
import ar.com.ford.it.webengine.websession.WebSession;

public class RequestsAction extends AbstractBaseAction {

    /**
     * Setea el mensaje de "busqueda sin resultados" cuando la busqueda no trae
     * resultados
     * 
     * @param request
     * Request donde se guarda el mensaje
     */
    private void searchWithNoResults(HttpServletRequest request) {
        ActionMessages am = new ActionMessages();
        MessageResources messageResources = (MessageResources) getResources(request);

        am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                "customMessage", messageResources
                        .getMessage("message.noResults")));
        saveMessages(request, am);
    }

    private Collection getStatusCombo(HttpServletRequest request) {
        LinkedList<OptionCombo> list = new LinkedList<OptionCombo>();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);

        list.add(new OptionCombo("P", resources
                .getMessage("request.label.pending")));
        list.add(new OptionCombo("R", resources
                .getMessage("request.label.rejected")));
        list.add(new OptionCombo("I", resources
                .getMessage("request.label.inProcess")));
        list.add(new OptionCombo("C", resources
                .getMessage("request.label.closed")));

        return list;
    }

    private Collection getUserFieldsCombo(HttpServletRequest request) {
        LinkedList<OptionCombo> list = new LinkedList<OptionCombo>();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);

        list.add(new OptionCombo("CR", resources
                .getMessage("user.label.creation")));
        list.add(new OptionCombo("CI", resources
                .getMessage("user.label.closure")));

        return list;
    }

    private Collection getDateFieldsCombo(HttpServletRequest request) {
        LinkedList<OptionCombo> list = new LinkedList<OptionCombo>();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);

        list.add(new OptionCombo("R", resources.getMessage("request.label")));
        list.add(new OptionCombo("C", resources
                .getMessage("user.label.closure")));

        return list;
    }

    public ActionForward initPage(FordActionMapping mapping,
                                  ActionForm actionForm,
                                  HttpServletRequest request,
                                  HttpServletResponse response,
                                  WebSession webSession, ActionMessages msgs,
                                  ActionMessages warns, ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        RequestsForm requestForm = (RequestsForm) actionForm;
        requestForm.resetForm();
        CommodityFacade commodityFacade = (CommodityFacade) FacadeProvider
                .getFacade(request, CommodityFacade.class);
        request.getSession().setAttribute("statusColl",
                this.getStatusCombo(request));
        request.getSession().setAttribute("userFields",
                this.getUserFieldsCombo(request));
        request.getSession().setAttribute("dateFields",
                this.getDateFieldsCombo(request));
        request.getSession().setAttribute("partClassColl",
                commodityFacade.getPartClases());
        try {
            request.getSession().setAttribute(
                    "commColl",
                    commodityFacade.findCommodities("", "", user
                            .getTeesg01Plant()));
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }

        return mapping.findForward("success");
    }

    public ActionForward cleanCreateFields(FordActionMapping mapping,
                                           ActionForm actionForm,
                                           HttpServletRequest request,
                                           HttpServletResponse response,
                                           WebSession webSession,
                                           ActionMessages msgs,
                                           ActionMessages warns,
                                           ActionMessages errorMsgs) {

        RequestsForm requestForm = (RequestsForm) actionForm;
        requestForm.cleanCreateFields();
        return mapping.findForward("success");
    }

    public ActionForward createRequest(FordActionMapping mapping,
                                       ActionForm actionForm,
                                       HttpServletRequest request,
                                       HttpServletResponse response,
                                       WebSession webSession,
                                       ActionMessages msgs,
                                       ActionMessages warns,
                                       ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        RequestsForm form = (RequestsForm) actionForm;
        RequestFacade requestFacade = (RequestFacade) FacadeProvider.getFacade(
                request, RequestFacade.class);
        SupplierFacade supplierFacade = (SupplierFacade) FacadeProvider
                .getFacade(request, SupplierFacade.class);
        String forward = "success";

        try {
            if (form.getEditBlocked().equalsIgnoreCase("false")) {
                Teess01Supplier supplier = new Teess01Supplier();
                supplier.setEess01SupplierClassCodeC(form.getSupplierClass());
                supplier.setEess01SupplierCodeC(form.getSupplierCode());
                supplier.setEess01PlantCodeC(user.getTeesg01Plant());
                supplier = supplierFacade.getSupplierByPk(supplier);
                if (supplier != null) {
                    Teesr01Request req = form.getRequestForCreate();
                    req.setTeess01Supplier(supplier);
                    req = requestFacade.createRequest(req, user);
                    request.setAttribute("requestSelected", req);
                } else {
                    am
                            .add(
                                    ActionMessages.GLOBAL_MESSAGE,
                                    new ActionMessage(
                                            "customMessage",
                                            resources
                                                    .getMessage("request.error.invalidSupplier")));
                    saveErrors(request, am);
                    forward = "error";
                }
            }
            if (form.getEditBlocked().equalsIgnoreCase("true")) {
                Teesr01Request req = form.getRequestForUpdate();
                requestFacade.updateRequest(req, user);
                request.setAttribute("requestSelected", req);
            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }

        return mapping.findForward(forward);
    }

    public ActionForward closeRequest(FordActionMapping mapping,
                                      ActionForm actionForm,
                                      HttpServletRequest request,
                                      HttpServletResponse response,
                                      WebSession webSession,
                                      ActionMessages msgs,
                                      ActionMessages warns,
                                      ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        RequestsForm form = (RequestsForm) actionForm;
        RequestFacade requestFacade = (RequestFacade) FacadeProvider.getFacade(
                request, RequestFacade.class);

        try {
            requestFacade.closeRequest(form.getRequestSelected()
                    .getEesr01RequestNumberK(), user);
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }

        return mapping.findForward("success");
    }

    public ActionForward deleteRequest(FordActionMapping mapping,
                                       ActionForm actionForm,
                                       HttpServletRequest request,
                                       HttpServletResponse response,
                                       WebSession webSession,
                                       ActionMessages msgs,
                                       ActionMessages warns,
                                       ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        RequestsForm form = (RequestsForm) actionForm;
        RequestFacade requestFacade = (RequestFacade) FacadeProvider.getFacade(
                request, RequestFacade.class);

        try {
            requestFacade.deleteRequest(form.getRequestSelected(form
                    .getSelectedIndex()));
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }

        return mapping.findForward("success");
    }

    public ActionForward findRequests(FordActionMapping mapping,
                                      ActionForm actionForm,
                                      HttpServletRequest request,
                                      HttpServletResponse response,
                                      WebSession webSession,
                                      ActionMessages msgs,
                                      ActionMessages warns,
                                      ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        RequestsForm form = (RequestsForm) actionForm;
        RequestFacade requestFacade = (RequestFacade) FacadeProvider.getFacade(
                request, RequestFacade.class);
        String forward = "success";

        try {
            RequestFindStruct findStruct = new RequestFindStruct();
            findStruct.setSupplierClass(form.getSupplierClassFind());
            findStruct.setSupplierCode(form.getSupplierCodeFind());
            findStruct.setSupplierName(form.getSupplierNameFind());
            findStruct.setCommodity(new Integer(form.getCommodityCode()));
            findStruct.setPartClass(form.getPartClass());
            findStruct.setPrefix(form.getPrefix());
            findStruct.setBase(form.getBase());
            findStruct.setSuffix(form.getSuffix());
            findStruct.setDateField(form.getDateFilter());
            findStruct.setUserField(form.getUserField());
            findStruct.setUserCode(form.getUserCode());
            if (!form.getDateFilter().equals("-1")) {
                findStruct.setDateFrom(new Timestamp(FullEconomicsDateUtil
                        .format(form.getDateFrom()).getTimeInMillis()));
                findStruct.setDateTo(new Timestamp(FullEconomicsDateUtil
                        .format(form.getDateTo()).getTimeInMillis()));
            }
            findStruct.setStatus(form.getStatus());
            findStruct.setPlant(user.getTeesg01Plant());
            form.setRequestColl(requestFacade.findRequests(findStruct));
            if (form.getRequestColl().isEmpty()) {
                searchWithNoResults(request);
            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }

        return mapping.findForward(forward);
    }

    public ActionForward editItems(FordActionMapping mapping,
                                   ActionForm actionForm,
                                   HttpServletRequest request,
                                   HttpServletResponse response,
                                   WebSession webSession, ActionMessages msgs,
                                   ActionMessages warns,
                                   ActionMessages errorMsgs) {

        RequestsForm form = (RequestsForm) actionForm;
        request.setAttribute("requestSelected", form.getRequestSelected());

        return mapping.findForward("success");
    }

    public ActionForward editRequest(FordActionMapping mapping,
                                     ActionForm actionForm,
                                     HttpServletRequest request,
                                     HttpServletResponse response,
                                     WebSession webSession,
                                     ActionMessages msgs, ActionMessages warns,
                                     ActionMessages errorMsgs) {

        RequestsForm form = (RequestsForm) actionForm;

        form
                .setRequestForEdit(form.getRequestSelected(form
                        .getSelectedIndex()));

        return mapping.findForward("success");
    }

    public ActionForward viewObs(FordActionMapping mapping,
                                 ActionForm actionForm,
                                 HttpServletRequest request,
                                 HttpServletResponse response,
                                 WebSession webSession, ActionMessages msgs,
                                 ActionMessages warns, ActionMessages errorMsgs) {

        RequestsForm form = (RequestsForm) actionForm;
        String selectedIndex = request.getParameter("selectedIndex");
        request.setAttribute("requestSelected", form
                .getRequestSelected(selectedIndex));

        return mapping.findForward("success");
    }
}
